package com.ruoyi.framework.interceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import com.ruoyi.common.utils.bean.BeanUtils;  
  
@Intercepts({  
    @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})  
})  
public class ResultInterceptor implements Interceptor {  
  
    @Override  
    public Object intercept(Invocation invocation) throws Throwable {  
        // 获取参数  
        Object[] args = invocation.getArgs();  
        MappedStatement mappedStatement = (MappedStatement) args[0];  
        Object parameter = args[1];  
        RowBounds rowBounds = (RowBounds) args[2];  
        ResultHandler resultHandler = (ResultHandler) args[3];  
        CacheKey cacheKey = (CacheKey) args[4];  
        BoundSql boundSql = (BoundSql) args[5];  
        
        // 调用原方法获取结果  
        Object result = invocation.proceed();  
  
        if (result instanceof List) {  
            List list = (List) result;
            if(list != null && list.size() > 0) {
            	Object obj = list.get(0);
            	if(obj instanceof java.util.Map) {
        			BeanUtils.caseFormat(list);
            	}
            }
        }  
  
        return result;  
    }  
  
    @Override  
    public Object plugin(Object target) {  
        // MyBatis 会自动处理这个方法，我们只需要返回 target 即可  
        return Plugin.wrap(target, this);  
    }  
  
    @Override  
    public void setProperties(Properties properties) {  
        // 可以在这里设置插件的属性，通过配置文件传入  
    }  
}